package nix.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import org.junit.Test;

public class Demo2 {

	@Test
	public void fun1() {
		Waiter waiter = new ManWaiter();
		waiter.serve();
	}

	/**
	 * 使用动态代理增强
	 */
	@Test
	public void fun2() {

		Waiter manWaiter = new ManWaiter();

		ClassLoader loader = this.getClass().getClassLoader();
		Class[] interfaces = { Waiter.class };
		InvocationHandler h = new WaiterInvocationHandler(manWaiter);
		// 代理对象
		Waiter waiter = (Waiter) Proxy.newProxyInstance(loader, interfaces, h);
		waiter.serve();
	}
}

class WaiterInvocationHandler implements InvocationHandler {
	// 目标对象
	private Waiter waiter;

	public WaiterInvocationHandler(Waiter waiter) {
		this.waiter = waiter;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {

		System.out.println("hello");
		// 目标方法被增强，调用
		this.waiter.serve();
		System.out.println("bye");

		return null;
	}

}
